/*
 *
 *  jQuery $.getImageData Plugin 0.3
 *  http://www.maxnov.com/getimagedata
 * 
 */

// Include dependencies
var express = require('express'),
request = require('request'),
http = require('http'),
URL = require('url');

// Create the server
var app = express.createServer(
	express.logger()
);

// When requesting the root
app.get('/', function(req, res){
	
	// If a URL and callback parameters are present 
	if(req.param("url") && req.param("callback")) {
		
		// Get the parameters
		var url = unescape(req.param("url")),
		callback = req.param("callback"),
		oURL = URL.parse(url),
		request = http.request({method:'GET', path: oURL.pathname, host: oURL.hostname});
		
		request.on('response', function (response)
		{
			var type = response.headers["content-type"],
				prefix = "data:" + type + ";base64,",
				body = "";
			
			response.setEncoding('binary');
			response.on('end', function () {
				var base64 = new Buffer(body, 'binary').toString('base64'),
					data = prefix + base64;
				var return_variable = {
					"width": 48,
					"height": 48,
					"data": data
				};
				return_variable = callback + "(" + JSON.stringify(return_variable) + ");";
				res.writeHead(200, {'Content-Type': 'application/javascript; charset=UTF-8'});
				res.end(return_variable);
			});
			response.on('data', function (chunk) {
				if (response.statusCode == 200) body += chunk;
			});
		});
		
		request.end();
	// Missing parameters	
	} else res.send("No URL or no callback was specified. These are required", 410);
	
});

// Handle 404 and 500 errors
app.get('/404', function(req, res){
	throw new Error('Page not found');
});
app.get('/500', function(req, res){
	throw new Error('Server error');
});

// Run the server on port 3000
app.listen(3000);
console.log('Server running at http://127.0.0.1:3000/');